import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../store/user'
import Users from '../views/Home.vue'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
import UserDetail from '../views/UserDetail.vue'
import ParkingSpaceManagement from '../views/ParkingSpaceManagement.vue'
import QuotaConsumptionMaintenance from '../views/QuotaConsumptionMaintenance.vue'
import Settings from '../views/Settings.vue'
import ApiTest from '../views/ApiTest.vue'

// 定义需要登录验证的路由
const authRoutes = ['/dashboard']

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    redirect: '/users'
  },
  {
    path: '/users',
    name: 'Users',
    component: Users,
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/user/:id',
    name: 'userDetail',
    component: UserDetail
  },
  {
    path: '/parking-spaces',
    name: 'ParkingSpaceManagement',
    component: ParkingSpaceManagement,
    meta: { requiresAuth: false }
  },
  {
    path: '/quota',
    name: 'QuotaConsumptionMaintenance',
    component: QuotaConsumptionMaintenance,
    meta: { requiresAuth: false }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: Settings,
    meta: { requiresAuth: false }
  },
  {
    path: '/api-test',
    name: 'ApiTest',
    component: ApiTest,
    meta: {
      requiresAuth: false,
      title: 'API测试',
      icon: 'api' // 根据您使用的图标库选择合适的图标
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫，检查登录状态
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 初始化用户状态
  if (!userStore.isLoggedIn) {
    userStore.initUserFromStorage()
  }
  
  // 检查路由是否需要身份验证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 如果需要登录但用户未登录或已过期，重定向到登录页
    if (!userStore.isLoggedIn) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next() // 已登录且未过期，正常进入
    }
  } else {
    // 如果已登录且尝试访问登录页，重定向到仪表盘
    if (to.path === '/login' && userStore.isLoggedIn) {
      next({ path: '/dashboard' })
    } else {
      next() // 不需要登录的页面，正常进入
    }
  }
})

export default router 